from flask import request
from flask_classy import  FlaskView, route

from ..schema.param import language_create_param
from ..schema.resp import language_list_schema, query_schema, language_schema
from ..services.language import LanguageService


class LanguagesView(FlaskView):
    @route('/<id>', methods=['DELETE'])
    def delete(self, id):
        language = LanguageService.get_by_id(id)
        if language:
            if not language.is_default():
                LanguageService.remove(language)
                return language_schema.jsonify(language)
        return 'ok'

    @route('/')
    def get_all(self):
        data, _ = language_list_schema.dump(LanguageService.filter())
        return query_schema.jsonify_with(items=data)

    @route('/<id>', methods=['POST'])
    def update(self, id):
        data, _ = language_create_param.load(request.get_json())
        data.pop('id', None)
        language = LanguageService.get_by_id(id)
        if language:
            language = LanguageService.update(id, data)
            return language_schema.jsonify(language)
        return 'ok'

    @route('/<id>')
    def get(self, id):
        language = LanguageService.get_by_id(id)
        return language_schema.jsonify(language)

    @route('/', methods=['POST'])
    def create(self):
        data, _ = language_create_param.load(request.get_json())

        language = LanguageService.create(**data)

        return language_schema.jsonify(language)
